<template>
  <div class="twobox">
    <div style="padding-bottom: 22px">
      <div style="float: left; font-size: 14px; color: #565c67">字段</div>
      <div style="float: right">
        <i
          class="el-icon-setting iconstyle"
          @click="setTableColumn()"
        ></i>
      </div>
    </div>
    <el-table
      :data="tableData"
      border
      show-header
      @selection-change="handleSelectionChange"
      max-height="380"
      row-key="index"
     class="ant-table-body tbody"
    @cell-dblclick="celldblclick"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column
        label="序号"
        align="center"
        fixed
        type="index"
        width="80"
      >
        <template slot-scope="scope">{{
          (scope.row.index = scope.$index + 1)
        }}</template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in currentColumn"
        :prop="item.prop"
        :label="item.label"
        :key="index"
        align="center"
        show-overflow-tooltip
      >
        <!-- @change="handleCheck(scope.row, scope.row.index)" -->
        <template slot-scope="scope">
          <span v-if="item.prop === 'notNull'">
            <el-checkbox disabled v-model="scope.row.notNull"></el-checkbox>
          </span>
          <span v-else-if="item.prop === 'isUnique'">
            <el-checkbox disabled v-model="scope.row.isUnique"></el-checkbox>
          </span>
          <span v-else-if="item.prop === 'inGlobalSearch'">
            <el-checkbox
              disabled
              v-model="scope.row.inGlobalSearch"
            ></el-checkbox>
          </span>
          <span v-else-if="item.prop === 'hideDays'">
            <el-checkbox disabled v-model="scope.row.hideDays"></el-checkbox>
          </span>
          <span v-else-if="item.prop === 'hideSeconds'">
            <el-checkbox disabled v-model="scope.row.hideSeconds"></el-checkbox>
          </span>
          <span v-else-if="item.prop === 'nonNegative'">
            <el-checkbox disabled v-model="scope.row.nonNegative"></el-checkbox>
          </span>
          <span v-else-if="item.prop === 'fetchIfEmpty'">
            <el-checkbox
              disabled
              v-model="scope.row.fetchIfEmpty"
            ></el-checkbox>
          </span>
          <!-- 是否自增 -->
          <span v-else-if="item.prop === 'isAutoIncrement'">
            <el-checkbox
              disabled
              v-model="scope.row.isAutoIncrement"
            ></el-checkbox>
          </span>
          <!-- 录入方式 -->
          <span v-else-if="item.prop === 'dataType'">
            <span v-show="scope.row.dataType == 0">手动录入</span>
            <span v-show="scope.row.dataType == 1">系统时间</span>
          </span>
          <!-- 格式 -->
          <span v-else-if="item.prop === 'chooseData'">
            <span>{{ scope.row.chooseData }}</span>
          </span>
          <span v-else>{{ scope.row[item.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作">
        <!-- <template slot="header">
          <i class="el-icon-setting iconstyle" v-if="inputStatus == 0"></i>
          <i
            class="el-icon-setting iconstyle"
            v-else
            @click="setTableColumn()"
          ></i>
        </template> -->
        <template slot-scope="scope">
          <i class="el-icon-edit-outline iconstyle" v-if="inputStatus == 0"></i>
          <i
            v-else
            class="el-icon-edit-outline iconstyle"
            @click="editRow(scope.row, scope.row.index)"
          ></i>
        </template>
      </el-table-column>
    </el-table>
    <el-button
      @click="deleterow"
      :disabled="multipleSelection.length < 1"
      class="deleteList"
      >删除</el-button
    >
    <el-button
      @click="add"
      type="primary"
      class="addList"
      >添加</el-button
    >

    <!-- 配置表头  -->
    <DynamicTable
      :inputStatus="inputStatus"
      :metadataId="metadataId"
      :allHeaderList="allHeaderList"
      :id="id"
      v-if="dynamicTableDialog"
      :detailflag="dynamicTableDialog"
      :checkedColumnList="checkedColumnList"
      @closeDynamicTable="closeDynamicTable"
    ></DynamicTable>
    <!--添加/编辑数据  -->
    <addEditInfo
      ref="addEditInfo"
      :inputStatus="inputStatus"
      :dialogflag="dialogVisible"
      :metadataId="metadataId"
      v-if="dialogVisible"
      @closedia="closedia"
      :dataObj="dataObj"
      :chooseDataList="chooseDataList"
      :tableData="tableData"
    ></addEditInfo>
    <div v-if="inputStatus == 1" slot="footer">
      <el-button type="primary" @click="preservation" class="dialog-footer"
        >保存</el-button
      >
    </div>
  </div>
</template>
<script>
import Sortable from 'sortablejs';
import DynamicTable from "./dialog/DynamicTable.vue";
import addEditInfo from "./dialog/addEditInfo.vue";
import {
  pageQuery,
  deleteInfo,
  getTableConfig,
  getTableHeader,
  Addfield,
  editFiled,
} from "@/api/metadata/metadata";
export default {
  components: {
    DynamicTable,
    addEditInfo,
  },
  props: {
    allList: {
      type: Object,
    },
  },
  data() {
    return {
      formData: {
        field101: [],
      },
      rules: {},
      //当前表格列
      currentColumn: [],
      //表格全部行数据
      tableData: [],
      dynamicTableDialog: false,
      dialogVisible: false,
      dataObj: {},
      ifChecked: false,
      //勾选的数据
      multipleSelection: [],
      //接受传过来的数据
      tableInfo: {},
      //状态
      inputStatus: "",
      // 查询参数
      queryParams: {
        current: 1,
        size: 1000,
        metadataId: "",
      },
      //配置表头要用的id做一下区分
      metadataId: "",
      //获取所有的表头信息
      allHeaderList: [],

      //选择列表
      checkedColumnList: [],
      //配置动态表头的元数据id
      id: "",
      //修改表格的申请
      queryALLTableInfo: [
        {
          chooseDataList: [],
          metadataFieldInfo: {},
        },
      ],
      //select 的选择
      chooseDataList: [],
      //传过来的数据综合
      metadataList: [],
      //编辑的时候得到的数组
      metadataInfoList: [],
    };
  },
  computed: {},
  watch: {},

  mounted() {
     //调用拖拽
    this.$nextTick(() => {     
        this.rowDrop()  
    });
    if (localStorage.getItem("status") == 2) {
      this.inputStatus = localStorage.getItem("status");
      this.getTableInfo();
      this.currentColumn = [
        {
          prop: "fieldName",
          label: "字段名",
        },
        {
          prop: "fieldType",
          label: "字段类型",
        },

        {
          prop: "fieldLabel",
          label: "字段标识",
        },
        {
          // 必填,0 否 / 1 是
          prop: "notNull",
          label: "必填",
        },
      ];
      // this.checkedColumnList = ["字段名", "字段类型", "字段标识", "必填"];
    } else {
      this.inputStatus = this.allList.status;
      this.tableInfo = this.allList.info;
      this.metadataId = this.tableInfo.id;
      //获取表头配置
      this.getTableInfo();
      //挂载完成以后赶紧去请求接口。
      //字段接口
      this.pageQueryList();
      //进来以后获取动态表头
    }
  },
  methods: {
    //拖拽的函数
    rowDrop() {
      const tbody = document.querySelector('.ant-table-body tbody')
      const _this = this
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.tableData.splice(oldIndex, 1)[0]
          _this.tableData.splice(newIndex, 0, currRow)
        }
      })
    },
    aaaa(val) {
      console.log(val, "val");
    },
    handleSizeChange() {},
    handleCurrentChange() {},
    //表格数据项勾选勾选
    handleCheck(row, index) {
      if (this.inputStatus == 2) {
        //新增元数据-编辑表格数据
        this.tableData.splice(index - 1, 1);
        this.tableData.splice(index - 1, 0, diaData);
      } else {
        //查看和编辑元数据-编辑表格数据
        console.log("操作编辑", row, index);
        this.closedia("编辑", row, index);
      }
    },
    //添加
    add() {
      this.dataObj = { flag: "add", index: this.tableData.length + 1 };
      // this.dataObj = { flag: "add", index: this.tableData.length + 1 };
      this.dialogVisible = true;
    },
    //编辑
    editRow(row, index) {
      this.dataObj = { flag: "edit", row, index };
      this.dialogVisible = true;
    },
    //关闭添加/编辑弹框
    closedia(title, diaData, index) {
      console.log(diaData, index, "父组件接收的数据");
      this.dialogVisible = false;
      if (diaData) {
        if (title === "编辑") {
          //编辑
          this.tableData.splice(index - 1, 1);
          this.tableData.splice(index - 1, 0, diaData);
        } else {
          if (this.inputStatus == 2) {
            //新建元数据-添加
            this.tableData.push(diaData);
            console.log(this.tableData, "this.tableData11111111");
          }
        }
        if (this.inputStatus == 1) {
          if (title === "添加") {
            for (let i in diaData) {
              if (diaData[i] == false) {
                diaData[i] = 0;
              }
              if (diaData[i] == true) {
                diaData[i] = 1;
              }
            }
          }

          this.queryALLTableInfo[0].metadataFieldInfo.choose = diaData.choose; //选择
          console.log(
            diaData.choose,
            diaData.linkOrTable,
            "diaData.linkOrTable+diaData.choose"
          );
          if (diaData.choose == 1) {
            this.queryALLTableInfo[0].chooseDataList = diaData.select;
            this.queryALLTableInfo[0].metadataFieldInfo.chooseData = "";
          } else if (diaData.choose == 0) {
            if (diaData.fieldType == "Datetime") {
              if (diaData.chooseData) {
                this.queryALLTableInfo[0].metadataFieldInfo.chooseData =
                  diaData.chooseData; //选择
              }
              this.queryALLTableInfo[0].metadataFieldInfo.dataType =
                diaData.dataType;
            } else {
              this.queryALLTableInfo[0].metadataFieldInfo.chooseData = "";
            }
          } else if (diaData.choose == 3 || diaData.choose == 4) {
            this.queryALLTableInfo[0].metadataFieldInfo.chooseData = "";
            this.queryALLTableInfo[0].chooseDataList = [
              {
                metadataLabel: diaData.linkOrTable, //元数据标识 下面那个选择的label
              },
            ];
          }  else if (diaData.choose == 5) {
            this.queryALLTableInfo[0].metadataFieldInfo.chooseData = "";
            this.queryALLTableInfo[0].chooseDataList = [
              {
                 metadataFieldLabel: diaData.dlinkListInfo, //元数据字段标识
              },
            ];
          }else {
            this.queryALLTableInfo[0].metadataFieldInfo.chooseData = "";
            this.queryALLTableInfo[0].chooseDataList = [
              {
                metadataLabel: diaData.metadataName, //元数据标识
                metadataFieldLabel: diaData.fetchFrom, //元数据字段标识
              },
            ];
          } //选择的数据
          // this.queryALLTableInfo[0].metadataFieldInfo.creation = ""; //创建时间
          if (diaData.defaultValue) {
            this.queryALLTableInfo[0].metadataFieldInfo.defaultValue =
              diaData.defaultValue; //默认值
          }
          if (diaData.description) {
            this.queryALLTableInfo[0].metadataFieldInfo.description =
              diaData.description; //描述
          }

          // this.queryALLTableInfo[0].metadataFieldInfo.docStatus = 0;
          this.queryALLTableInfo[0].metadataFieldInfo.fetchFrom =
            diaData.fetchFrom; //从其他元数据获取字段
          this.queryALLTableInfo[0].metadataFieldInfo.fetchIfEmpty =
            diaData.fetchIfEmpty; //尽在没有输入该值的时候获取
          this.queryALLTableInfo[0].metadataFieldInfo.fieldLabel =
            diaData.fieldLabel; //字段标识
          this.queryALLTableInfo[0].metadataFieldInfo.fieldName =
            diaData.fieldName; //字段名
          this.queryALLTableInfo[0].metadataFieldInfo.fieldType =
            diaData.fieldType; //字段类型
          this.queryALLTableInfo[0].metadataFieldInfo.idx = index; //序号
          // this.queryALLTableInfo[0].metadataFieldInfo.hideDays=diaData.hideDays;//隐藏天
          // this.queryALLTableInfo[0].metadataFieldInfo.hideSeconds=diaData.hideSeconds;//隐藏秒
          if (title == "编辑") {
            this.queryALLTableInfo[0].metadataFieldInfo.id = diaData.id;
          } else {
            this.queryALLTableInfo[0].metadataFieldInfo.id = ""; //元数据字段id
          }
          // this.queryALLTableInfo[0].metadataFieldInfo.inGlobalSearch=diaData.inGlobalSearch;//关键字搜索
          this.queryALLTableInfo[0].metadataFieldInfo.isDel = 0; //逻辑删除预留
          this.queryALLTableInfo[0].metadataFieldInfo.length = parseInt(
            diaData.length
          ); //长度
          this.queryALLTableInfo[0].metadataFieldInfo.metadataId =
            this.metadataId;
          this.queryALLTableInfo[0].metadataFieldInfo.metadataName =
            diaData.metadataName;
          // this.queryALLTableInfo[0].metadataFieldInfo.modified = ""; //修改时间
          this.queryALLTableInfo[0].metadataFieldInfo.modifiedBy = ""; //修改人
          this.queryALLTableInfo[0].metadataFieldInfo.moduleName = "";
          // this.queryALLTableInfo[0].metadataFieldInfo.nonNegative=diaData.nonNegative;//非负数
          // this.queryALLTableInfo[0].metadataFieldInfo.notNull=diaData.notNull;
          this.queryALLTableInfo[0].metadataFieldInfo.options = ""; //字段类型扩张预留
          this.queryALLTableInfo[0].metadataFieldInfo.owner = ""; //拥有者
          this.queryALLTableInfo[0].metadataFieldInfo.precision = parseInt(
            diaData.precision
          ); //精度
          console.log(
            this.queryALLTableInfo[0].metadataFieldInfo,
            diaData.listValueCheck,
            "this.queryALLTableInfo[0].metadataFieldInfo"
          );
          if (diaData.listValueCheck == 0) {
            this.queryALLTableInfo[0].metadataFieldInfo.notNull = 0; //必填
            this.queryALLTableInfo[0].metadataFieldInfo.inGlobalSearch = 0; //关键字
            this.queryALLTableInfo[0].metadataFieldInfo.hideDays = 0; //隐藏天
            this.queryALLTableInfo[0].metadataFieldInfo.hideSeconds = 0; //隐藏秒
            this.queryALLTableInfo[0].metadataFieldInfo.nonNegative = 0; //非负数
            this.queryALLTableInfo[0].metadataFieldInfo.isUnique = 0; //唯一
            this.queryALLTableInfo[0].metadataFieldInfo.isAutoIncrement = 0; //自增
          } else {
            this.queryALLTableInfo[0].metadataFieldInfo.notNull =
              diaData.listValueCheck.indexOf("notNull") != -1 ? 1 : 0; //必填
            this.queryALLTableInfo[0].metadataFieldInfo.inGlobalSearch =
              diaData.listValueCheck.indexOf("inGlobalSearch") != -1 ? 1 : 0; //关键字
            this.queryALLTableInfo[0].metadataFieldInfo.hideDays =
              diaData.listValueCheck.indexOf("hideDays") != -1 ? 1 : 0; //隐藏天
            this.queryALLTableInfo[0].metadataFieldInfo.hideSeconds =
              diaData.listValueCheck.indexOf("hideSeconds") != -1 ? 1 : 0; //隐藏秒
            this.queryALLTableInfo[0].metadataFieldInfo.nonNegative =
              diaData.listValueCheck.indexOf("nonNegative") != -1 ? 1 : 0; //非负数
            this.queryALLTableInfo[0].metadataFieldInfo.isUnique =
              diaData.listValueCheck.indexOf("isUnique") != -1 ? 1 : 0; //唯一
            this.queryALLTableInfo[0].metadataFieldInfo.isAutoIncrement =
              diaData.listValueCheck.indexOf("isAutoIncrement") != -1 ? 1 : 0; //自增
          }

          if (title == "编辑") {
            let obj = {
              chooseDataList: this.queryALLTableInfo[0].chooseDataList,
              metadataFieldInfo: this.queryALLTableInfo[0].metadataFieldInfo,
            };
            this.metadataInfoList.push(obj);
          }
          console.log(this.queryALLTableInfo, "this.queryALLTableInfo00000");
          if (title == "添加") {
            Addfield(this.queryALLTableInfo)
              .then((response) => {
                if (response.success) {
                  this.$modal.msgSuccess("添加成功");
                  this.pageQueryList();
                }
              })
              .catch((err) => {
                // this.$message.error(err.message);
                console.log(err);
              });
          }
        }
      }
    },
    //获取表头配置
    getTableInfo() {
      getTableConfig()
        .then((response) => {
          this.allHeaderList = response.data;
          if (this.inputStatus != 2) {
            //再去获取动态表头 然后对比
            this.getTableTou();
          }
        })
        .catch((err) => {
          // this.$message.error(err.message);
          console.log(err);
        });
    },
    //获取动态表头
    getTableTou() {
      if (this.inputStatus != 2) {
        //不是新建
        let getHeader = { metadataId: this.metadataId };
        getTableHeader(getHeader)
          .then((response) => {
            if (response.data) {
              this.id = response.data.id;
              let headerList = response.data.headerList;
              //编辑 -获取的列头数据
              this.currentColumn = [];
              headerList.forEach((item) => {
                this.allHeaderList.forEach((i) => {
                  if (item == i.prop) {
                    this.currentColumn.push(i);
                    this.checkedColumnList.push(i.label);
                  }
                });
              });
              this.checkedColumnList = [...new Set(this.checkedColumnList)];
            }
          })
          .catch((err) => {
            // this.$message.error(err.message);
            console.log(err);
          });
      }
    },
    //获取（编辑）表格字段
    pageQueryList() {
      this.queryParams.metadataId = this.tableInfo.id;
      pageQuery(this.queryParams)
        .then((response) => {
          if (response.success) {
            let aeeList = response.data.dataList;
            if (aeeList) {
              this.metadataList = [];
              this.chooseDataList = [];
              aeeList.forEach((item) => {
                this.metadataList.push(item.metadataFieldInfo);
                this.chooseDataList.push(item.chooseDataList);
              });
              this.metadataList.forEach((item) => {
                item.fetchIfEmpty = item.fetchIfEmpty == 1 ? true : false;
                item.hideSeconds = item.hideSeconds == 1 ? true : false;
                item.hideDays = item.hideDays == 1 ? true : false;
                item.inGlobalSearch = item.inGlobalSearch == 1 ? true : false;
                item.isUnique = item.isUnique == 1 ? true : false;
                item.isAutoIncrement = item.isAutoIncrement == 1 ? true : false;
                item.notNull = item.notNull == 1 ? true : false;
              });
              this.tableData = this.metadataList;
            } else {
              this.tableData = [];
            }

            console.log(this.tableData, "一进来获取的表格数据");
            // this.$modal.msgSuccess("修改成功");
            //   this.$router.go(-1)
            // if (this.tableData.notNull == 0) {
            //   this.tableData.notNull = false;
            // } else {
            //   this.tableData.notNull = true;
            // }
          }
        })
        .catch((err) => {
          // this.$message.error(err.message);
          console.log(err);
        });
    },
    //配置表头
    setTableColumn() {
      console.log("this.currentColumn", this.currentColumn);
      console.log("this.allHeaderList", this.allHeaderList);
      this.currentColumn.forEach((item) => {
        this.allHeaderList.forEach((i) => {
          if (item.prop == i.prop) {
            this.currentColumn.push(i);
            this.checkedColumnList.push(i.label);
          }
        });
      });
      this.dynamicTableDialog = true;
    },
    //关闭配置表头弹框
    closeDynamicTable(arr) {
      this.dynamicTableDialog = false;
      if (arr) {
        this.currentColumn = arr;
      }
    },
    //勾选change
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //删除元数据字段信息
    deleterow() {
      if (this.inputStatus == 2) {
        this.$modal.confirm("是否永久删除？删除后将无法恢复").then(() => {
          for (let i = 0; i < this.multipleSelection.length; i++) {
            this.multipleSelection.forEach((row, index) => {
              this.tableData.forEach((v, i) => {
                if (row.fieldName === v.fieldName) {
                  // i 为选中的索引
                  this.tableData.splice(i, 1);
                }
              });
            });
          }
          this.multipleSelection = []; // 删除完数据之后清除勾选框
        });
      } else if (this.inputStatus == 1) {
        let pastid = {
          ids: [],
        };
        for (let i = 0; i < this.multipleSelection.length; i++) {
          pastid.ids.push(this.multipleSelection[i].id);
        }
        this.$modal.confirm("是否永久删除？删除后将无法恢复").then(() => {
          deleteInfo(pastid)
            .then((response) => {
              if (response.success) {
                this.$modal.msgSuccess("删除成功");
              }
              this.pageQueryList();
            })
            .catch(() => {});
        });
      }
    },
    //保存修改
    preservation() {
      console.log(this.metadataInfoList, "this.metadataInfoList");
      this.metadataInfoList.forEach((item) => {
        for (let i in item.metadataFieldInfo) {
          if (item.metadataFieldInfo[i] == false) {
            item.metadataFieldInfo[i] = 0;
          }
          if (item.metadataFieldInfo[i] == true) {
            item.metadataFieldInfo[i] = 1;
          }
        }
      });
      this.metadataInfoList = [...new Set(this.metadataInfoList)];
      console.log(this.metadataInfoList, "this.metadataInfoList2222");

      editFiled(this.metadataInfoList)
        .then((response) => {
          if (response.success) {
            this.$modal.msgSuccess("保存成功");
            this.$router.push("/metadata/metadataList");
          }
        })
        .catch((err) => {
          // this.$message.error(err.message);
          console.log(err);
        });
    },
    //实现双击复制时间
    celldblclick(row, column, cell, event){
      if( event.type === "dblclick"){
        var rowType=column.property;
        var save = function (e){         
          e.clipboardData.setData('text/plain',row[rowType]);
          e.preventDefault();//阻止默认行为
        }
        // 添加copy事件
        document.addEventListener('copy',save);
        //复制选中的文字到剪贴板;
        document.execCommand("copy");
        //移除addEventListener的事件
        document.removeEventListener('copy',save);
      }
      //复制成功后提示
      this.$message({message: "复制 "+row[rowType]+" 成功", type:'success'}) 
    },
  },
};
</script>
<style lang="scss" scoped>
@import "~@/assets/styles/mixin.scss";
@import "~@/assets/styles/variables.scss";
.twobox {
  width: 56%;
  margin: 40px auto 70px;
  // margin: 40px 211px 50px 211px;
}
::v-deep .el-table__fixed-right {
  width: 115px;
}
::v-deep.el-table--striped
  .el-table__body
  tr.el-table__row--striped
  td.el-table__cell {
  background-color: #f2f6fc !important;
}
::v-deep .el-table .cell {
  padding: 5px;
}
::v-deep .el-table th.el-table__cell > .cell {
  font-size: 14px;
  color: #565c67;
}
::v-deep .el-table td.el-table__cell {
  padding: 2px !important;
}
::v-deep .el-table__row {
  height: 50px;
}
//选择框的样式更改
::v-deep .el-checkbox .el-checkbox__inner {
  width: 20px;
  height: 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f7f7f7;
}
::v-deep .el-checkbox .is-checked .el-checkbox__inner {
  background-color: #dcdfe6;
}
::v-deep .el-checkbox .is-checked .el-checkbox__inner::after {
  height: 15px;
  width: 8px;
  border-color: #fff;
  top: -3px;
}
::v-deep .iconstyle {
  font-size: 25px !important;
}
.addList {
  width: 70px;
  height: 40px;
  margin-top: 10px;
  color: #fff;
  background-color: $labelColor;
  border-radius: 4px;
  font-size: 14px;
}
.deleteList {
  font-size: 14px;
  width: 70px;
  height: 40px;
  margin-top: 10px;
  color: $labelColor;
  border-color: #dcdfe6;
  border-radius: 4px;
}
.iconstyle {
  font-size: 18px;
  cursor: pointer;
  color: #d8e2f0;
}
.dialog-footer {
  width: 122px;
  height: 40px;
  background-color: $labelColor;
  color: #fff;
  font-size: 16px;
  margin-top: 80px;
  border-color: #e8eaec;
  border-radius: 4px;
}
</style>
